#include "Common.h"
#include "SkeletonManager.h"
#include "Skeleton.h"
#include "MeshSerializer.h"

SkeletonManager::SkeletonManager(void)
{
}

SkeletonManager::~SkeletonManager(void)
{
	RemoveAll();
}

Skeleton* SkeletonManager::Create(const std::string& name)
{
	if (GetByName(name) != NULL)
		return NULL;

	Skeleton* mesh = new Skeleton(name);
	mSkeletons[name] = mesh;

	return mesh;
}

Skeleton* SkeletonManager::Load(const std::string& name)
{
	Skeleton* ret = GetByName(name);
	if (ret != NULL)
		return ret;

	ret = Create(name);

	MeshSerializer ser;
	if (!ser.ImportSkeleton(name, ret))
	{
		RemoveByName(name);
		return NULL;
	}

	return ret;
}

Skeleton* SkeletonManager::GetByName(const std::string& name)
{
	SkeletonMap::iterator it = mSkeletons.find(name);
	if (it != mSkeletons.end())
		return it->second;
	return NULL;
}

bool SkeletonManager::RemoveByName(const std::string& name)
{
	SkeletonMap::iterator it = mSkeletons.find(name);
	if (it == mSkeletons.end())
		return false;

	delete it->second;
	mSkeletons.erase(it);
	return true;
}

void SkeletonManager::RemoveAll()
{
	for (SkeletonMap::iterator it(mSkeletons.begin()), end(mSkeletons.end()); it != end; it++)
		delete it->second;
	mSkeletons.clear();
}
